# -*- coding: UTF-8 -*-
import mqtt
import ujson
import utime as time
import _thread




#==========================================================
#填入MQTT信息
AccessToken = "5i17at8qwqd6v8e4"
ProjectKey = 'JMN1q5sITR'
mqttaddr = "bj-3-mqtt.iot-api.com"
serverport = 1883
#==========================================================


#服务质量
qos = 0
#topic
_get_topic = "attributes/push" 
_update_topic = "attributes"  #上报属性
mqtt_state = 0


# 定义subcribe的回调函数
def on_subcribe(topic,payload):
    global client
    global update_topic
    print("on_subcribe: topic is:" + topic)
    print("on_subcribe: payload is:" + payload)
    #平台下发的信息
    cloudmsg = ujson.loads(payload)
    print(cloudmsg)

def mqttloop_func(delay, id):
    global client
    global mqtt_state
    while True:
        time.sleep_ms(delay)
        # print('Running thread %d'%id)
        ret = client.loop(1000)
        # print('client ret ={}'.format(ret))
        if ret < 0:
            print('------------------mqtt disconnect!')
            mqtt_state = 0
            client.disconnect()
            mqtt_reconnect()
        else:
            pass

def get_mqtt_state():
    global mqtt_state
    return mqtt_state


def mqtt_reconnect():
    global client
    global mqtt_state
    global update_topic

    clientId = "hass506"       #可填写任意名称
    hearttime = 40
    #订阅/发布的topic
    get_topic = _get_topic
    update_topic = _update_topic

    client = mqtt.client(clientId)
    client.on_subcribe(on_subcribe)

    # 设置用户名和密码
    client.username_pw_set(AccessToken,ProjectKey)
    # 建立mqtt连接
    ret = client.connect(mqttaddr,serverport,hearttime)
    if ret == 0:
        mqtt_state = 1
    # 订阅服务
    client.subscribe(get_topic,qos)
    # 发布服务
    client.publish(update_topic,update_data(),qos)

def mqtt_connect():
    mqtt_reconnect()
    #创建mqtt接收数据任务，1s一次（2号线程）
    _thread.start_new_thread(mqttloop_func,(1000, 2))

def update_data():
    # cTemp,humidity = sht30_drv.get_temp_humidity() 
    send_data = {
        "humidity":40,
        "temperature":30,
    }
    #上报 格式 可以参考这句话
    MSG = ujson.dumps(send_data)
    return MSG

def update():
    global client
    client.publish(update_topic,update_data(),qos)